package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> listAll() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {
        Query query = new Query();
        // 查询总条数
       /* long count = template.count(query, Region.class);
        if(count == 0){
            return Page.empty();
        }*/
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
       /* query.with(pageable);
        List<Region> list = template.find(query, Region.class);*/
        return DBHelper.query(template,pageable,query,Region.class,qo);
    }

    @Override
    public void changeHotValue(int hot, String id) {
        // 查询
       /* Region region = this.get(id);
        // 替换
        region.setIshot(hot);
        // 更新
        this.update(region);*/
       // 部分字段更新
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,Region.class);
    }

    @Override
    public List<Region> queryhotRegion() {
        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }
}
